package _4_multithread.basic;

/**
 * Created by bpzj on 6/24/2018.
 */
public class SimpleWN {

    final static Object object = new Object();
    private final static long start = System.currentTimeMillis();

    public static class T1 implements Runnable {
        @Override
        public void run() {
            synchronized (object) {
                System.out.println((System.currentTimeMillis() - start) / 1000 + " s: T1 start!");
                try {
                    System.out.println((System.currentTimeMillis() - start) / 1000 + " s: T1 wait for object");
                    // wait会释放锁，所以wait 5秒期间，线程 t2会获得锁
                    object.wait(5000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println((System.currentTimeMillis() - start) / 1000 + " s: T1 end");
            }
        }
    }

    public static class T2 implements Runnable {
        @Override
        public void run() {
            synchronized (object) {
                System.out.println((System.currentTimeMillis() - start) / 1000 + " s: T2 start");
                // notify 在此处，因 T1 中，wait(5000) ，但，没到5s，就notify，所以 T1 在 T2 sleep 2s后，会唤醒，向下执行
                // 如果不加 object.notify() 就要等 5s 超时后，T1才能唤醒并向下执行
                // System.out.println((System.currentTimeMillis() - start) / 1000 + " s: T2 notify object");
                // object.notify();
                try {
                    // sleep 不会释放锁，所以在sleep 2秒期间， t1 也不会获得锁
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println((System.currentTimeMillis() - start) / 1000 + " s: T2 end");
            }
        }
    }

    public static void main(String[] args) {
        Thread t1 = new Thread(new T1());
        Thread t2 = new Thread(new T2());
        t1.start();
        t2.start();
    }

    // wait() 方法可以用 notify 方法唤醒
    // wait 会释放目标对象的锁，sleep 不会释放任何资源


}
